package logic

import (
	"context"
	"zye1/user_srv/user"

	"zye1/api/internal/svc"
	"zye1/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterCodeUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterCodeUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterCodeUserLogic {
	return &RegisterCodeUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterCodeUserLogic) RegisterCodeUser(req *types.RegisterCodeUserRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 短信账号密码注册

	//判断短信验证码 (查询短信验证码)
	code, err := l.svcCtx.UserSrv.GetSmsCode(l.ctx, &user.GetSmsCodeRequest{
		Mobile: req.Mobile,
		Sale:   "reg",
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}
	//判断短信验证码是否匹配
	if req.Code != code.Code {
		return &types.RegMsgResponse{
			Cre:  -2,
			Msg:  "短信验证错误",
			Data: nil,
		}, err
	}

	//实现注册
	_, err = l.svcCtx.UserSrv.RegisterCodeUser(l.ctx, &user.RegisterCodeUserRequest{
		Mobile:   req.Mobile,
		Code:     req.Code,
		Username: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Msg:  "注册失败",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre:  0,
		Msg:  "注册成功",
		Data: nil,
	}, err
}
